import re
from rest_framework import serializers
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
from settings.offline_config import *
from django.contrib.auth import authenticate
from . import models

class LoginModelSerializer(serializers.ModelSerializer):
    # post请求，序列化默认当做create动作进行校验，需要校验数据库，create动作username会抛用户已存在异常
    # 抛用户已存在异常是多余的，所以自定义系统校验规则即可
    # 限制用户名密码长度
    username = serializers.CharField(min_length=3, max_length=16)
    password = serializers.CharField(min_length=8, max_length=16)
    class Meta:
        model = models.User
        fields = ['username', 'password']

    # 用全局钩子，完成token的签发,attrs是反序列化后的数据以类似字典的形式存在
    def validate(self, attrs):
        # 1）通过 username 和 password 完成登录校验，得到user的model对象
        user = self.validate_user(attrs)
        # 2）user对象包装payload载荷,JWT的第二部分,内置方法一定要user对象
        payload = jwt_payload_handler(user)
        # 3）payload载荷签发token,JWT的第三部分,加密完成后将三部分以.拼接得到JWT整体
        token = jwt_encode_handler(payload)
        # 4）将user与token存储到serializer对象中，方便在视图类中使用
        self.content = {
            'user': user,
            'token': token,
            'icon': BASE_URL+MEDIA_URL+str(user.icon),
        }
        return attrs

    #验证账户是否存在
    def validate_user(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        credentials = {
            'username':username,
            'password': password
        }
        user = authenticate(**credentials)
        if user is None:
            raise serializers.ValidationError({'message': '用户信息异常'})

        return user

class RegisterUserModelSerializer(serializers.ModelSerializer):
    # write_only是只写不能读，可以理解为只能前台到后台，在后台做了逻辑操作后直接存数据库,如果是校验数据
    # 则直接pop掉该数据,校验数据时不会校验second_password字段
    #read_only 是只读，不能写（可以理解为只能从后台到前台，后台操作后直接传前台）,不参与数据库的交互，后台直接定义返回给前台
    #如attr["username"]="AAAA"即可只是赋予并不存数据库做一次性校验可以使用

    second_password = serializers.CharField(min_length=8, max_length=16,write_only=True)
    password = serializers.CharField(min_length=8, max_length=16,write_only=True)
    username = serializers.CharField(min_length=8, max_length=16)
    class Meta:
        model = models.User
        fields = ['username', 'password','second_password','mobile']




    #全局钩子可以拿到全部属性
    def validate(self, attrs):
        password=attrs.get('password')
        second_password=attrs.get('second_password')
        if password!=second_password:
            raise serializers.ValidationError({'msg': '两次密码不一致'})
        attrs.pop('second_password')
        return attrs

    # create方法是是需要重写：默认入库，密码是明文
    def create(self, validated_data):
        # post请求，序列化默认当做create动作进行校验
        return models.User.objects.create_user(**validated_data)

class ChangeUserModelSerializer(serializers.ModelSerializer):
    password = serializers.CharField(min_length=8, max_length=16,write_only=True)
    username = serializers.CharField(min_length=8, max_length=16)
    mobile = serializers.CharField(min_length=11, max_length=11,write_only=True)
    class Meta:
        model = models.User
        fields = ['username', 'password','mobile']



    def validate(self, attrs):
        username=attrs['username']
        mobile=attrs['mobile']
        password=attrs['password']
        user = models.User.objects.filter(username=username,mobile=mobile).first()
        if user:
            user.set_password(password)
            user.save()
        self.content = {
            'user': user,
        }
        return attrs



